<template>
  <div class="discovery">
    <scroll
      ref="scroll"
      pullDown
      pullUpLoad
      @pullingDown='pullingDown'
      @pullingUp='pullingUp'
      stop-propagation
      :preventDefault='false'
      :data='modules'
    >
      <van-swipe :autoplay="3000" indicator-color='red' class="banner">
        <van-swipe-item v-for="(banner, index) in bannerList" :key="index">
          <img :src="banner.pic" class="banner-image" />
        </van-swipe-item>
      </van-swipe>

      <div class="balls-Box">
        <ul class="balls-list">
          <li class="ball" v-for="(ball, index) of balls" :key="index" @click="clickBall(ball.url)">
            <div class="ball__icon">
              <img :src="ball.iconUrl" />
              <span class="ball__icon__day" v-if="index === 0">{{ ball.day }}</span>
            </div>
            <span class="ball__name">{{ ball.name }}</span>
          </li>
        </ul>
      </div>

      <component
        v-for="(moduleInfo, index) of modules"
        :key="index"
        :is="moduleInfo.module"
        :name='moduleInfo.name'
        @onClickRefresh='onClickRefresh'
      />
    </scroll>
    <transition name="enter">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive" />
      </keep-alive>
    </transition>
    <transition name="enter">
      <router-view v-if="!$route.meta.keepAlive"/>
    </transition>
  </div>
</template>
<script>
import { banner } from 'api/banner'
import navigator from '@/utils/navigator'
import Card from 'base/card'
import Scroll from 'base/scroll'
import { mapActions } from 'vuex'
import { getNotRepeatNum } from '@/utils/index'
import { ball } from 'api/homepage'

export default {
  components: {
    Card,
    Scroll
  },
  data() {
    return {
      balls: [],
      bannerList: [],
      modules: [],
      moduleConfigs: [],
      max: 3,
      catListCount: 4 // 随机获取分类数量
    }
  },
  computed: {
    width() {
      return window.screen.width * 0.3
    },
    ballWidth() {
      return window.screen.width / this.balls.length
    }
  },
  mounted() {
    this.getBannerData()
    this.getBall()
    this.getCatlistData()
  },
  methods: {
    getCatlistData(fn) {
      // this.moduleConfigs.push({
      //   moduleName: 'paly-list',
      //   name: 'recommend'
      // })
      // this.loadModules().finally(() => {
      //   if (typeof fn === 'function') fn()
      // })

      this.getCatlist().then(catlist => {
        const randomNums = getNotRepeatNum(0, catlist.length - 1, this.catListCount)
        for (let index = 0; index < this.catListCount; index++) {
          this.moduleConfigs.push({
            moduleName: index % 2 === 0 ? 'paly-list' : 'song',
            name: index === 0 ? 'recommend' : catlist[randomNums[index]].name
          })
        }

        this.moduleConfigs.push({ moduleName: 'disc' })
        this.moduleConfigs.push({ moduleName: 'rank' })
        this.moduleConfigs.push({ moduleName: 'station' })
        this.moduleConfigs.push({ moduleName: 'more' })

        this.loadModules().finally(() => {
          if (typeof fn === 'function') fn()
        })
      })
    },
    getBannerData() {
      let type = 0
      if (navigator.Android()) {
        type = 1
      } else if (navigator.iPhone()) {
        type = 2
      } else if (navigator.iPad()) {
        type = 3
      }
      banner(type).then(res => {
        this.bannerList = res.banners
      })
    },
    getBall() {
      ball().then(res => {
        let balls = res.data || []
        balls[0].day = new Date().getDate()
        this.balls = balls
      })
    },
    clickBall(url) {
      let reg = /^orpheus:\/\//
      if (reg.test(url)) {
        url = url.replace(reg, '').replace('discovery/', '')
        this.$router.push(`/discovery/${url}`)
      }
    },
    pullingDown(finish) {
      this.refresh(finish)
    },
    pullingUp(finish) {
      this.loadModules().finally(() => {
        finish()
      })
    },
    refresh(fn) {
      this.modules = []
      this.moduleConfigs = []
      this.getCatlistData(fn)
    },
    onClickRefresh() {
      this.$refs.scroll.scrollTo()
      this.refresh()
    },
    async loadModules() {
      if (!this.moduleConfigs.length) return
      for (let index = 0; index < this.max; index++) {
        const config = this.moduleConfigs.shift()
        if (!config) break
        this.modules.push({
          module: await this.getModule(config.moduleName),
          name: config.name
        })
      }
      this.$refs.scroll.refresh()
    },
    getModule(moduleName) {
      return new Promise((resolve) => {
        resolve(() => import(`./modules/${moduleName}.vue`))
      }).catch(err => {
        console.log(err)
        console.log('导入模块失败')
      })
    },
    ...mapActions(['getCatlist'])
  }
}
</script>
<style lang="less" scoped>
@import '~@/style/variable.less';
.discovery{
  height: 100%;
  .banner{
    height: 150px;
    &-image{
      width: 100%;
    }
  }
  .balls-Box{
    width: 100%;
    overflow-x: auto;
    .balls-list{
      display: inline-block;
      white-space:nowrap;
      .ball{
        display: inline-block;
        padding: 8px;
        text-align: center;
        .ball__icon{
          position: relative;
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: @primary-color;
          .ball__icon__day{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-40%);
            color: @primary-color;
          }
          >img{
            width: 100%;
            height: 100%;
            border-radius: 50%
          }
        }
        .ball__name{
          display: block;
          margin-top: 5px;
        }
      }
    }
  }
  .balls-Box::-webkit-scrollbar{width:0;}
}
</style>